package com.leyou.user.service.Impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.service.UserService;
import com.leyou.user.util.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceimpl implements UserService {
    static final Logger logger = LoggerFactory.getLogger(UserService.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;

    private String KEY_PREFIX="user:code:phone:";

    @Override
    public Boolean checkData(String data, Integer type) {
        //校验用户数据是否唯一,用户名和手机号码
        User user =new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw  new LyException(ExceptionEnum.BAD_REQUEST);
        }
        return userMapper.selectCount(user) == 0;
    }

    @Override
    public Boolean sendVerifyCode(String phone) {
        String key=KEY_PREFIX+phone;
        if (!phone.matches("^1[3456789]\\d{9}$")) {
            throw new LyException(HttpStatus.BAD_REQUEST,"手机号码不正确!");
        }
        //生成随机验证码
        String code = NumberUtils.generateCode(6);
        try{
            //发送mq, 给sms发短信
            HashMap<String ,String> map = new HashMap<>();
            map.put("phone",phone);
            map.put("code",code);
            amqpTemplate.convertAndSend("ly.sms.exchange","sms.verify.code",map);
            //验证码存redis
            redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
            return true;
        }catch (Exception e){
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }


    }

    @Override
    public Boolean register(User user, String code) {
        String key =KEY_PREFIX+user.getPhone();
        //从redis取出验证码
        String codeCache = this.redisTemplate.opsForValue().get(key);
        //检查验证码是否正确
        if(!code.equals(codeCache)){
            //并不正确，返回
        }
        user.setId(null);
        user.setCreated(new Date());
        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        //对密码加密
        String md5Hex = CodecUtils.md5Hex(user.getPassword(), user.getSalt());
        user.setPassword(md5Hex);
        // 写入数据库
        boolean boo = this.userMapper.insertSelective(user) == 1;
        if(boo){
            try {
                this.redisTemplate.delete(key);
            }catch (Exception e){
                logger.error("删除缓存验证码失败，code：{}", code, e);
            }
        }
        return boo;
    }

    @Override
    public User queryUserByUsernameAndPassword(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }
        //首先根据用户名查询用户
        User user = userMapper.queryUserByUserName(username);
        if (user == null) {
            throw new LyException(ExceptionEnum.USER_NOT_EXIST);
        }
        //检验密码是否正确
        if (!StringUtils.equals(CodecUtils.md5Hex(password,user.getSalt()),user.getPassword())) {
            //密码不正确
            throw new LyException(ExceptionEnum.PASSWORD_NOT_MATCHING);
        }
        System.out.println("user++++++++"+user);
        return user;

    }

    public User queryUser(String username, String password) {
        User record = new User();
        record.setUsername(username);

        //首先根据用户名查询用户
        User user = userMapper.selectOne(record);

        if (user == null) {
            throw new LyException(ExceptionEnum.USER_NOT_EXIST);
        }

        //检验密码是否正确
        if (!StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword())) {
            //密码不正确
            throw new LyException(ExceptionEnum.PASSWORD_NOT_MATCHING);
        }

        return user;
    }

}